<template>
  <div class="app-container">
    <!-- 主体内容 -->
    <div class="main-content">
      <!-- 分类管理 -->
      <div class="content-wrapper">
        <el-card>
          <div class="table-header">
            <el-button type="primary" size="small" @click="handleAdd">
              新增
            </el-button>
            <el-input
                v-model="searchKey"
                placeholder="请输入搜索内容"
                clearable
                style="width: 200px; margin-left: 10px"
                @keyup.enter="fetchData"
            >
              <template prefix>
                <i class="el-icon-search"></i>
              </template>
            </el-input>
            <el-button type="primary" @click="fetchData()">搜索</el-button>
          </div>

          <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="name" label="分类名称" />
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)"
                >编辑</el-button
                >
                <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.row.id)"
                >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
              v-model:current-page="pagination.current"
              :page-size="pagination.size"
              :total="pagination.total"
              layout="prev, pager, next"
              @current-change="handlePageChange"
          />
        </el-card>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
      </el-form>
<!--      自定义脚页-->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import request from "@/utils/request.js";

// 路由实例
const router = useRouter()

// 响应式数据
const user = ref(JSON.parse(localStorage.getItem('user')))
const authority = ref([])
const permission = ref([])
const searchKey = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('新增分类')
const formRef = ref(null)  // 表单引用

// 表格数据
const tableData = ref([])
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据和校验规则
const form = reactive({
  id: null,
  name: ''
})

const rules = reactive({
  name: [
    { required: true, message: '分类名称不能为空', trigger: 'blur' }
  ]
})

// 生命周期钩子
onMounted(() => {
  fetchData()
  loadPermissions()
})

// 加载权限
async function loadPermissions() {
  try {
    const [permRes, authRes] = await Promise.all([
      request.get('/permission/3'),
      request.get('/authority')
    ])

    if (permRes.data.code === '0') permission.value = permRes.data.data
    if (authRes.data.code === '0') authority.value = authRes.data.data
  } catch (error) {
    ElMessage.error('权限加载失败')
  }
}

// 加载表格数据
async function fetchData() {
  try {
    const name = searchKey.value || 'all';
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size
    }
    const res = await request.get(`/typeInfo/page/${name}`, { params });
    if (res.data.code === '0') {
      tableData.value = res.data.data.list
      pagination.total = res.data.data.total
    }
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}

// 分页变化
function handlePageChange(page) {
  pagination.current = page
  fetchData()
}

// 新增
function handleAdd() {
  if (!checkPermission(1)) {
    ElMessage.warning('没有操作权限')
    return
  }
  Object.assign(form, { id: null, name: '' })
  dialogTitle.value = '新增分类'
  dialogVisible.value = true
}

// 处理编辑
function handleEdit(row) {
  if (!checkPermission(3)) {
    ElMessage.warning('没有操作权限')
    return
  }
  Object.assign(form, row)
  dialogTitle.value = '编辑分类'
  dialogVisible.value = true
}

// 提交表单
async function submitForm() {
  // 表单校验
  try {
    await formRef.value.validate()
  } catch (error) {
    ElMessage.error('请填写完整信息')
    return
  }

  try {
    const url = form.id ? '/typeInfo' : '/typeInfo'
    const method = form.id ? 'put' : 'post'

    const res = await request[method](url, form)
    if (res.data.code === '0') {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      await fetchData()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 处理删除
async function handleDelete(id) {
  if (!checkPermission(2)) {
    ElMessage.warning('没有操作权限')
    return
  }

  try {
    await ElMessageBox.confirm('确认删除该分类吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await request.delete(`/typeInfo/${id}`)
    ElMessage.success('删除成功')
    await fetchData()
  } catch (error) {
    // 取消删除不处理
  }
}

// 权限检查
function checkPermission(code) {
  return permission.value.includes(code)
}
</script>

<style scoped>

.app-container {
  display: flex;
  min-height: 100vh;
}

.side-menu-container {
  width: 200px;
  background: #f5f5f5;
}

.main-content {
  flex: 1;
  padding: 20px;
}


.table-header {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

</style>